// src/service/album/index.js
const { blog_album, album_category, blog_photo } = require("@/model");
const { Sequelize } = require("sequelize");
const { deleteQiniuFile } = require('@/utils/qiniuUpload');

class AlbumService {
  async createAlbum(data) {
    return await blog_album.create(data);
  }

  async saveAlbum(data) {
    return await blog_album.upsert(data)
  }

  async getAlbums({ pageSize, pageIndex } = {}) {
    const query = {
      include: [
        {
          model: album_category,
          as: "album_category",
          attributes: [],
        },
      ],
      attributes: {
        include: [
          [Sequelize.col("album_category.name"), "categoryName"]
        ],
      },
      order: [["updatedAt", "DESC"]],
    };

    if (pageSize && pageIndex) {
      query.limit = pageSize;
      query.offset = (pageIndex - 1) * pageSize;
    }

    const res = await blog_album.findAndCountAll(query);

    // 获取所有相册id
    const albumIds = res.rows.map(album => album.id);

    // 统计每个相册的图片数量
    let photoCounts = {};
    if (albumIds.length) {
      const photos = await blog_photo.findAll({
        attributes: [
          "albumId",
          [Sequelize.fn("COUNT", Sequelize.col("id")), "count"]
        ],
        where: { albumId: albumIds },
        group: ["albumId"]
      });
      photoCounts = photos.reduce((acc, item) => {
        acc[item.albumId] = parseInt(item.get("count"), 10);
        return acc;
      }, {});
    }

    // 查每个相册的第一张图片作为封面
    let covers = {};
    if (albumIds.length) {
      // 这里用原生SQL或子查询效率更高，Sequelize简单写法如下
      const firstPhotos = await blog_photo.findAll({
        attributes: [
          "albumId",
          [Sequelize.fn("MIN", Sequelize.col("id")), "minId"]
        ],
        where: { albumId: albumIds },
        group: ["albumId"]
      });
      const minIdArr = firstPhotos.map(item => item.get("minId"));
      if (minIdArr.length) {
        const coverPhotos = await blog_photo.findAll({
          attributes: ["albumId", "url"],
          where: { id: minIdArr }
        });
        covers = coverPhotos.reduce((acc, item) => {
          acc[item.albumId] = item.url;
          return acc;
        }, {});
      }
    }

    // 组装返回数据
    const list = res.rows.map(album => {
      const data = album.toJSON();
      data.count = photoCounts[album.id] || 0;
      if (!data.cover) {
        data.cover = covers[album.id] || null;
      }
      return data;
    });

    return {
      total: res.count,
      list,
      pageIndex: pageIndex || 1,
      totalPage: pageSize ? Math.ceil(res.count / pageSize) : 1,
    };
  }

  async getAlbumById(id) {
    return await blog_album.findOne({
      where: { id },
      include: [
        {
          model: album_category,
          as: "album_category",
          attributes: ["id", "name"],
        },
      ],
    });
  }

  async updateAlbum(id, data) {
    const album = await this.getAlbumById(id);
    if (!album) throw new Error("相册不存在");
    return await album.update(data);
  }

  async deleteAlbum(id) {
    const album = await this.getAlbumById(id);
    if (!album) throw new Error("相册不存在");
    return await album.destroy();
  }
  async deletePhoto(id) {
    // 删除七牛云上的图片
    const photo = await blog_photo.findOne({ where: { id } });
    const res = await blog_photo.destroy({ where: { id } });
    if (photo && photo.url) {
      // 从URL中提取文件名
      const key = photo.url.replace(/^https?:\/\/[^/]+\//, '');
      await deleteQiniuFile(key);
    }
    return res;
  }

  // 分类相关
  async saveCategory(data) {
    return await album_category.upsert(data);
  }

  async getCategories() {
    const res = await album_category.findAndCountAll();
    const { count, rows } = res;
    return {
      total: count,
      list: rows
    };
  }

  async getCategoryById(id) {
    return await album_category.findOne({ where: { id } });
  }

  async deleteCategory(id) {
    const category = await this.getCategoryById(id);
    if (!category) throw new Error("分类不存在");
    return await category.destroy();
  }

  async savePhoto(params) {
    return await blog_photo.create(params);
  }

  async getPhotoList({ pageSize = 10, pageIndex = 1, ...other }) {
    const offset = (pageIndex - 1) * pageSize;
    const res = await blog_photo.findAndCountAll({
      limit: pageSize,
      offset,
      where: { ...other },
    });
    return {
      total: res.count,
      list: res.rows,
      pageIndex,
      totalPage: Math.ceil(res.count / pageSize),
    }
  }

}

module.exports = new AlbumService();